from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.generic import create_update
from django.views.generic import list_detail
from django.shortcuts import get_object_or_404

from hosting.hosts.forms import AddHostForm
from hosting.hosts.forms import UpdateHostForm
from hosting.hosts.models import Host
from hosting.hosts.models import HostAlias
from hosting.profiles.models import Profile


@login_required
def index(request):
    return HttpResponseRedirect(reverse(list_hosts))

@login_required
def list_hosts(request):
    extra_context = { 'form': AddHostForm() }
    if "status" in request.session:
        extra_context['status'] = request.session.get("status")
        extra_context['message'] = request.session.get("message")
        del request.session["status"]
        del request.session["message"]
    return list_detail.object_list(
        request,
        queryset = Host.objects.filter(user=request.user),
        template_object_name = 'hosts',
        extra_context = extra_context
    )

@login_required
def host_detail(request, host_id):
    if request.method == 'POST':
        return update_host(request, host_id)
    user = request.user
    host = get_object_or_404(Host, user=user,pk=host_id)
    extra_context = { 'host': host }
    return create_update.update_object(
            request,
            form_class = UpdateHostForm,
            object_id = host.id,
            extra_context = extra_context
    )

@login_required
def add_host(request):
    user = request.user
    if request.method == 'POST':
        form = AddHostForm(request.POST)
        if form.is_valid():
            user_profile = Profile.objects.get(user=user)
            hostname = form.cleaned_data['host']
            email = form.cleaned_data.get('email','postmaster@'+hostname)
            if user_profile is None:
                request.session["status"] = False
                request.session["message"] = "Host "+hostname+" can't added. No tarif"
            else:
                if user_profile.sites_used < user_profile.plan.sites_max:
                    host = Host(user=user,name=hostname,email=email,status=1)
                    host.save()
                    alias = HostAlias(host=host,name='www.'+hostname)
                    alias.save()
                    request.session["status"] = True
                    request.session["message"] = "Host "+hostname+" added"
                    user_profile.sites_used += 1
                    user_profile.save()
                else:
                    request.session["status"] = False
                    request.session["message"] = "Host "+hostname+" can't added. Max sites reached"
        else:
            request.session["status"] = False
            request.session["message"] = form.errors['host']
    return HttpResponseRedirect(reverse(list_hosts))


@login_required
def update_host(request, host_id):
    user = request.user
    update_host = Host.objects.get(user=user,pk=host_id)
    form = UpdateHostForm(request.POST, instance=update_host)
    if form.is_valid():
        form.save()
        request.session["status"] = True
        request.session["message"] = "Host "+update_host.name+" modifed"
    return HttpResponseRedirect(reverse(list_hosts))

@login_required
def delete_host(request, host_id):
    user = request.user
    delete_host = Host.objects.get(user=user,pk=host_id)
    user_profile = Profile.objects.get(user=user)
    if request.method == 'POST':
        request.session["status"] = True
        request.session["message"] = "Host "+delete_host.name+" deleted"
        delete_host.delete()
        user_profile.sites_used -= 1
        user_profile.save()
    return HttpResponseRedirect(reverse(list_hosts))


@login_required
def list_host_aliases(request, host_id):
    user = request.user
    host = Host.objects.get(user=user,pk=host_id)
    extra_context = { 'form': AddHostForm(), 'host': host }
    if "status" in request.session:
        extra_context['status'] = request.session.get("status")
        extra_context['message'] = request.session.get("message")
        del request.session["status"]
        del request.session["message"]

    return list_detail.object_list(
        request,
        queryset = HostAlias.objects.filter(host=host.id),
        template_object_name = 'host_aliases',
        extra_context = extra_context
    )

@login_required
def add_host_alias(request, host_id):
    if request.method == 'POST':
        form = AddHostForm(request.POST)
        if form.is_valid():
            alias_name = form.cleaned_data['host']
            host_alias = HostAlias(host_id=host_id,name=alias_name)
            host_alias.save()
            request.session["status"] = True
            request.session["message"] = "Alias "+host_alias.name+" added"
    return HttpResponseRedirect(reverse(list_host_aliases, args=[host_id]))

@login_required
def delete_host_alias(request, host_id, alias_id):
    user = request.user
    host = Host.objects.get(user=user,pk=host_id)
    delete_host_alias = HostAlias.objects.get(host=host,pk=alias_id)
    if request.method == 'POST':
        request.session["status"] = True
        request.session['message'] = 'Alias'+delete_host_alias.name+' deleted'
        delete_host_alias.delete()
    return HttpResponseRedirect(reverse(list_host_aliases, args=[host_id]))
